package com.zrh.jsd.service.studydemo.ThreadLocalTest;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalId {
    private static final AtomicInteger nextId = new AtomicInteger();

    private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
        protected Integer initialValue() {
            return nextId.getAndIncrement();
        }
    };

    public static int get() {
        return threadId.get();
    }

    public static void remove() {
        threadId.remove();
    }

    private static void incrementSameThreadId() {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread() + "_" + i + ",threadId:" + ThreadLocalId.get());
            }
        } finally {
            ThreadLocalId.remove();
        }
    }

    public static void main(String[] args) {
        incrementSameThreadId();
        new Thread(()->{
            incrementSameThreadId();
        }).start();
        new Thread(()->{
            incrementSameThreadId();
        }).start();
        // 结论：不同线程间的id不同，相同线程id相同。


        Thread t = Thread.currentThread();

        ThreadLocal threadLocal1 = new ThreadLocal();
        threadLocal1.set("llllll");
        ThreadLocal threadLocal = new ThreadLocal();
        threadLocal.set("12345");
        System.out.println(threadLocal1.get());

        System.out.println(threadLocal.get());
        threadLocal.set("agcsda");
        System.out.println(threadLocal.get());
    }
}
